<template>
  <div class="behavior-orchestration-panel">
    <!-- 工具栏 -->
    <div class="toolbar">
      <a-space>
        <a-button type="primary" @click="showCreateModal">
          <template #icon>
            <IconifyIcon icon="ant-design:cluster-outlined" />
          </template>
          新建编排
        </a-button>
        <a-button @click="refreshData">
          <template #icon>
            <IconifyIcon icon="ant-design:reload-outlined" />
          </template>
          刷新
        </a-button>
      </a-space>

      <a-space>
        <a-input-search
          :value="searchKeyword"
          placeholder="搜索编排流程"
          style="width: 200px"
          @search="handleSearch"
        />
        <a-select
          :value="filterStatus"
          placeholder="编排状态"
          style="width: 150px"
          @change="handleFilter"
        >
          <a-select-option value="">全部状态</a-select-option>
          <a-select-option
            v-for="status in orchestrationStatuses"
            :key="status.value"
            :value="status.value"
          >
            {{ status.label }}
          </a-select-option>
        </a-select>
      </a-space>
    </div>

    <!-- 编排流程列表 -->
    <a-table
      :columns="columns"
      :data-source="orchestrations"
      :loading="loading"
      :pagination="pagination"
      row-key="id"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'status'">
          <a-tag :color="getStatusColor(record.status)">
            {{ getStatusLabel(record.status) }}
          </a-tag>
        </template>

        <template v-else-if="column.key === 'type'">
          <a-tag :color="getTypeColor(record.type)">
            {{ getTypeLabel(record.type) }}
          </a-tag>
        </template>

        <template v-else-if="column.key === 'actions'">
          <a-space>
            <a-button type="link" size="small" @click="showDetailModal(record)">
              详情
            </a-button>
            <a-button type="link" size="small" @click="showDesignModal(record)">
              设计
            </a-button>
            <a-button
              v-if="record.status === 'ENABLED'"
              type="link"
              size="small"
              @click="handleExecute(record.id)"
            >
              执行
            </a-button>
            <a-popconfirm
              title="确定要删除这个编排流程吗？"
              @confirm="handleDelete(record.id)"
            >
              <a-button type="link" size="small" danger>删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 编排详情模态框 -->
    <a-modal
      :open="detailModalVisible"
      title="编排详情"
      width="900px"
      @cancel="closeDetailModal"
      :footer="null"
    >
      <div v-if="selectedOrchestration">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="编排名称">
            {{ selectedOrchestration.name }}
          </a-descriptions-item>
          <a-descriptions-item label="编排代码">
            {{ selectedOrchestration.code }}
          </a-descriptions-item>
          <a-descriptions-item label="编排类型">
            <a-tag :color="getTypeColor(selectedOrchestration.type)">
              {{ getTypeLabel(selectedOrchestration.type) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="编排状态">
            <a-tag :color="getStatusColor(selectedOrchestration.status)">
              {{ getStatusLabel(selectedOrchestration.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ selectedOrchestration.createdAt }}
          </a-descriptions-item>
          <a-descriptions-item label="描述" :span="2">
            {{ selectedOrchestration.description || '-' }}
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>

    <!-- 编排详情模态框 -->
    <a-modal
      :open="detailModalVisible"
      title="编排详情"
      width="900px"
      @cancel="closeDetailModal"
      :footer="null"
    >
      <div v-if="selectedOrchestration">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="编排ID">
            {{ selectedOrchestration?.id }}
          </a-descriptions-item>
          <a-descriptions-item label="编排名称">
            {{ selectedOrchestration?.name }}
          </a-descriptions-item>
          <a-descriptions-item label="编排类型">
            <a-tag :color="getTypeColor(selectedOrchestration?.type)">
              {{ getTypeLabel(selectedOrchestration?.type) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="编排状态">
            <a-tag :color="getStatusColor(selectedOrchestration?.status)">
              {{ getStatusLabel(selectedOrchestration?.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ selectedOrchestration?.createdAt }}
          </a-descriptions-item>
          <a-descriptions-item label="更新时间">
            {{ selectedOrchestration?.updatedAt }}
          </a-descriptions-item>
          <a-descriptions-item label="描述" :span="2">
            {{ selectedOrchestration?.description }}
          </a-descriptions-item>
        </a-descriptions>

        <a-divider />

        <a-tabs>
          <a-tab-pane key="flow" tab="流程设计">
            <div class="flow-design">
              <a-steps direction="vertical" size="small">
                <a-step
                  v-for="step in selectedOrchestration?.steps || []"
                  :key="step.id"
                  :title="step.name"
                  :description="step.description"
                  :status="getStepStatus(step.status)"
                >
                  <template #icon>
                    <IconifyIcon :icon="getStepIcon(step.type)" />
                  </template>
                </a-step>
              </a-steps>
            </div>
          </a-tab-pane>

          <a-tab-pane key="conditions" tab="条件配置">
            <a-list>
              <a-list-item
                v-for="condition in selectedOrchestration?.conditions || []"
                :key="condition.id"
              >
                <a-list-item-meta>
                  <template #title>{{ condition.name }}</template>
                  <template #description>{{ condition.description }}</template>
                </a-list-item-meta>
                <template #actions>
                  <a-tag :color="getConditionTypeColor(condition.type)">
                    {{ getConditionTypeLabel(condition.type) }}
                  </a-tag>
                </template>
              </a-list-item>
            </a-list>
          </a-tab-pane>

          <a-tab-pane key="executions" tab="执行历史">
            <a-table
              :columns="executionColumns"
              :data-source="selectedOrchestration?.executions || []"
              :pagination="false"
              size="small"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'status'">
                  <a-tag :color="getStatusColor(record.status)">
                    {{ getStatusLabel(record.status) }}
                  </a-tag>
                </template>
              </template>
            </a-table>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-modal>

    <!-- 流程设计器模态框 -->
    <a-modal
      :open="designModalVisible"
      title="行为编排设计器"
      width="95vw"
      :footer="null"
      :body-style="{ height: '80vh', padding: '0' }"
      @cancel="closeDesignModal"
    >
      <BehaviorOrchestrationDesigner
        v-if="designModalVisible"
        :orchestration-id="selectedOrchestration?.id"
        :resource-id="resourceId"
        :resource-type="resourceType"
        @orchestration-saved="handleOrchestrationSaved"
        @orchestration-tested="handleOrchestrationTested"
      />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { message } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';
import BehaviorOrchestrationDesigner from './BehaviorOrchestrationDesigner.vue';

// Props
interface Props {
  resourceId: string;
  resourceType: string;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  'orchestration-created': [orchestration: any];
  'orchestration-executed': [orchestrationId: string];
}>();

// 响应式数据
const loading = ref(false);
const orchestrations = ref<any[]>([]);
const searchKeyword = ref('');
const filterStatus = ref('');
const detailModalVisible = ref(false);
const designModalVisible = ref(false);
const selectedOrchestration = ref<any>(null);

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 编排状态选项
const orchestrationStatuses = computed(() => [
  { value: 'DRAFT', label: '草稿' },
  { value: 'ENABLED', label: '已启用' },
  { value: 'DISABLED', label: '已禁用' },
  { value: 'RUNNING', label: '执行中' },
  { value: 'COMPLETED', label: '已完成' },
  { value: 'FAILED', label: '执行失败' },
]);

// 可用行为组件
const availableBehaviors = computed(() => [
  { id: '1', name: '资源启动', description: '启动指定资源', type: 'START' },
  { id: '2', name: '资源配置', description: '配置资源参数', type: 'CONFIGURE' },
  { id: '3', name: '资源备份', description: '备份资源数据', type: 'BACKUP' },
  { id: '4', name: '资源监控', description: '监控资源状态', type: 'MONITOR' },
  { id: '5', name: '通知发送', description: '发送通知消息', type: 'NOTIFY' },
]);

// 表格列定义
const columns = [
  {
    title: '编排名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: '编排类型',
    dataIndex: 'type',
    key: 'type',
    width: 120,
  },
  {
    title: '编排状态',
    dataIndex: 'status',
    key: 'status',
    width: 120,
  },
  {
    title: '步骤数量',
    dataIndex: 'stepCount',
    key: 'stepCount',
    width: 100,
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 180,
    customRender: ({ text }: { text: string }) =>
      new Date(text).toLocaleString(),
  },
  {
    title: '更新时间',
    dataIndex: 'updatedAt',
    key: 'updatedAt',
    width: 180,
    customRender: ({ text }: { text: string }) =>
      new Date(text).toLocaleString(),
  },
  {
    title: '操作',
    key: 'actions',
    width: 250,
    fixed: 'right',
  },
];

// 执行历史表格列
const executionColumns = [
  {
    title: '执行ID',
    dataIndex: 'id',
    key: 'id',
    width: 120,
  },
  {
    title: '开始时间',
    dataIndex: 'startTime',
    key: 'startTime',
    width: 180,
    customRender: ({ text }: { text: string }) =>
      new Date(text).toLocaleString(),
  },
  {
    title: '结束时间',
    dataIndex: 'endTime',
    key: 'endTime',
    width: 180,
    customRender: ({ text }: { text: string }) =>
      text ? new Date(text).toLocaleString() : '-',
  },
  {
    title: '执行状态',
    dataIndex: 'status',
    key: 'status',
    width: 120,
  },
];

// 方法
const loadData = async () => {
  loading.value = true;
  try {
    // 模拟数据
    const mockData = [
      {
        id: 'orch-001',
        name: '资源部署流程',
        type: 'SEQUENTIAL',
        status: 'ENABLED',
        stepCount: 5,
        description: '完整的资源部署流程，包括启动、配置、备份、监控和通知',
        createdAt: new Date(Date.now() - 86400000).toISOString(),
        updatedAt: new Date(Date.now() - 3600000).toISOString(),
        steps: [
          {
            id: '1',
            name: '资源启动',
            description: '启动目标资源',
            type: 'START',
            status: 'SUCCESS',
          },
          {
            id: '2',
            name: '资源配置',
            description: '配置资源参数',
            type: 'CONFIGURE',
            status: 'SUCCESS',
          },
          {
            id: '3',
            name: '资源备份',
            description: '备份当前状态',
            type: 'BACKUP',
            status: 'SUCCESS',
          },
          {
            id: '4',
            name: '资源监控',
            description: '启动监控',
            type: 'MONITOR',
            status: 'RUNNING',
          },
          {
            id: '5',
            name: '通知发送',
            description: '发送部署完成通知',
            type: 'NOTIFY',
            status: 'PENDING',
          },
        ],
        conditions: [
          {
            id: '1',
            name: '资源可用性检查',
            description: '检查资源是否可用',
            type: 'PRECONDITION',
          },
          {
            id: '2',
            name: '配置验证',
            description: '验证配置参数',
            type: 'VALIDATION',
          },
        ],
        executions: [
          {
            id: 'exec-001',
            startTime: new Date(Date.now() - 300000).toISOString(),
            endTime: new Date(Date.now() - 240000).toISOString(),
            status: 'SUCCESS',
          },
          {
            id: 'exec-002',
            startTime: new Date(Date.now() - 60000).toISOString(),
            endTime: null,
            status: 'RUNNING',
          },
        ],
      },
      {
        id: 'orch-002',
        name: '资源维护流程',
        type: 'PARALLEL',
        status: 'DRAFT',
        stepCount: 3,
        description: '并行执行的资源维护流程',
        createdAt: new Date(Date.now() - 172800000).toISOString(),
        updatedAt: new Date(Date.now() - 7200000).toISOString(),
        steps: [
          {
            id: '1',
            name: '数据备份',
            description: '备份重要数据',
            type: 'BACKUP',
            status: 'PENDING',
          },
          {
            id: '2',
            name: '系统更新',
            description: '更新系统组件',
            type: 'UPDATE',
            status: 'PENDING',
          },
          {
            id: '3',
            name: '性能优化',
            description: '优化系统性能',
            type: 'OPTIMIZE',
            status: 'PENDING',
          },
        ],
        conditions: [],
        executions: [],
      },
    ];

    orchestrations.value = mockData;
    pagination.total = mockData.length;
  } catch (error) {
    message.error('加载编排流程失败');
    console.error('加载编排流程失败:', error);
  } finally {
    loading.value = false;
  }
};

const refreshData = () => {
  loadData();
};

const handleSearch = () => {
  pagination.current = 1;
  loadData();
};

const handleFilter = () => {
  pagination.current = 1;
  loadData();
};

const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadData();
};

const showCreateModal = () => {
  message.info('新建编排功能开发中...');
};

const showDetailModal = (orchestration: any) => {
  selectedOrchestration.value = orchestration;
  detailModalVisible.value = true;
};

const closeDetailModal = () => {
  detailModalVisible.value = false;
  selectedOrchestration.value = null;
};

const showDesignModal = (orchestration: any) => {
  selectedOrchestration.value = orchestration;
  designModalVisible.value = true;
};

const closeDesignModal = () => {
  designModalVisible.value = false;
  selectedOrchestration.value = null;
};

const handleExecute = async (id: string) => {
  try {
    message.success('开始执行编排流程');
    emit('orchestration-executed', id);
    loadData();
  } catch (error) {
    message.error('执行编排流程失败');
    console.error('执行编排流程失败:', error);
  }
};

const handleDelete = async (id: string) => {
  try {
    message.success('删除成功');
    loadData();
  } catch (error) {
    message.error('删除失败');
    console.error('删除编排流程失败:', error);
  }
};

const addBehaviorToFlow = (behavior: any) => {
  message.info(`添加行为组件: ${behavior.name}`);
};

const getStatusLabel = (status: string) => {
  const found = orchestrationStatuses.value.find((s) => s.value === status);
  return found ? found.label : status;foundfound.labelfoundfound.label
};

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    DRAFT: 'default',
    ENABLED: 'success',
    DISABLED: 'warning',
    RUNNING: 'processing',
    COMPLETED: 'success',
    FAILED: 'error',
  };
  return colorMap[status] || 'default';
};

const getTypeLabel = (type: string) => {
  const labelMap: Record<string, string> = {
    SEQUENTIAL: '顺序执行',
    PARALLEL: '并行执行',
    CONDITIONAL: '条件执行',
    LOOP: '循环执行',
  };
  return labelMap[type] || type;
};

const getTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    SEQUENTIAL: 'blue',
    PARALLEL: 'green',
    CONDITIONAL: 'orange',
    LOOP: 'purple',
  };
  return colorMap[type] || 'default';
};

const getStepStatus = (status: string) => {
  if (status === 'SUCCESS') return 'finish';
  if (status === 'RUNNING') return 'process';
  if (status === 'FAILED') return 'error';
  return 'wait';
};

const getStepIcon = (type: string) => {
  const iconMap: Record<string, string> = {
    START: 'ant-design:play-circle-outlined',
    CONFIGURE: 'ant-design:setting-outlined',
    BACKUP: 'ant-design:save-outlined',
    MONITOR: 'ant-design:eye-outlined',
    NOTIFY: 'ant-design:notification-outlined',
    UPDATE: 'ant-design:sync-outlined',
    OPTIMIZE: 'ant-design:thunderbolt-outlined',
  };
  return iconMap[type] || 'ant-design:question-circle-outlined';
};

const getConditionTypeLabel = (type: string) => {
  const labelMap: Record<string, string> = {
    PRECONDITION: '前置条件',
    VALIDATION: '验证条件',
    POSTCONDITION: '后置条件',
  };
  return labelMap[type] || type;
};

const getConditionTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    PRECONDITION: 'blue',
    VALIDATION: 'green',
    POSTCONDITION: 'orange',
  };
  return colorMap[type] || 'default';
};

const handleOrchestrationSaved = (orchestration: any) => {
  message.success('编排保存成功');
  closeDesignModal();
  loadData();
  emit('orchestration-created', orchestration);
};

const handleOrchestrationTested = (result: any) => {
  message.success('编排测试完成');
  console.log('测试结果:', result);
};

// 生命周期
onMounted(() => {
  loadData();
});
</script>

<style lang="less" scoped>
.behavior-orchestration-panel {
  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 16px;
    background: #fafafa;
    border-radius: 6px;
  }

  .flow-design {
    .flow-canvas {
      min-height: 400px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>
